/*
 * 文件名：BuildController.java
 * 版权：Copyright by www.infopub.top
 * 描述：
 * 修改人：chenhan
 * 修改时间：2020年1月10日
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package top.infopub.mgr.ic.web;


import com.github.pagehelper.Page;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import top.infopub.mgr.bpa.service.ContractExtService;
import top.infopub.mgr.bpa.service.InnerAgrtService;
import top.infopub.mgr.bpa.service.ProContractInvestService;
import top.infopub.mgr.bpa.service.ProContractService;
import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.mgr.hr.service.StaffInfoService;
import top.infopub.mgr.ic.domain.BuildInfoDomain;
import top.infopub.mgr.ic.service.BuildInfoService;
import top.infopub.mgr.ic.service.MonthCtrlMileService;
import top.infopub.mgr.ic.service.MonthCtrlService;
import top.infopub.mgr.ic.vo.BuildInfoVo;
import top.infopub.mgr.ic.vo.BuildSaveVo;
import top.infopub.mgr.mkt.service.DiscloseProService;
import top.infopub.mgr.mkt.vo.DiscloseProVo;
import top.infopub.mgr.util.FileHelper;
import top.infopub.mgr.util.LogUtil;
import top.infopub.model.hr.StaffInfo;
import top.infopub.model.mkt.DisclosePro;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.util.IdFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 投建基本信息
 * @author chenhan
 * @version 2020年1月10日
 * @see BuildInfoController
 * @since
 */
@Controller
@RequestMapping("/buildInfo")
public class BuildInfoController extends GenericFlowController {
    
    @Autowired
    private BuildInfoService buildInfoService;

    @Autowired
    private StaffInfoService staffInfoService;

    @Autowired
    private DiscloseProService discloseProService;

    @Autowired
    private ProContractService proContractService;

    @Autowired
    private ProContractInvestService proContractInvestService;

    @Autowired
    private ContractExtService contractExtService;

    @Autowired
    private InnerAgrtService innerAgrtService;

    @Autowired
    private MonthCtrlService monthCtrlService;

    @Autowired
    private MonthCtrlMileService monthCtrlMileService;

    /**
     * 投建管理列表
     *
     * @return
     * @see
     */
    @RequestMapping("/list")
    public String list() {
        return "ic/lay-buildInfo-list";
    }

    /**
     * 建投项目管理列表
     *
     * @param buildInfoVo
     * @param paramPage
     * @return
     */
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<BuildInfoDomain> queryDataByCondition(BuildInfoVo buildInfoVo, ParamPage paramPage) {
        Page<BuildInfoDomain> page = new Page<BuildInfoDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        if (buildInfoVo.getBuildBeginEndDate() != null) {
            buildInfoVo.setBuildBeginEndDate(DateUtils.addDays(buildInfoVo.getBuildBeginEndDate(),
                1));
        }
        if (buildInfoVo.getBuildBeginEndDate() != null) {
            buildInfoVo.setBuildBeginEndDate(DateUtils.addDays(buildInfoVo.getBuildBeginEndDate(),
                1));
        }
        if (buildInfoVo.getBuildFinishEndDate() != null) {
            buildInfoVo.setBuildFinishEndDate(DateUtils.addDays(
                buildInfoVo.getBuildFinishEndDate(), 1));
        }
        page = buildInfoService.selectByDomainWhere(page, buildInfoVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 查询我审批的建投项目
     *
     * @param buildInfoVo
     * @param paramPage
     * @return
     */
    @RequestMapping("/queryMyCheckDataByCondition")
    @ResponseBody
    public RspVo<BuildInfoDomain> queryMyCheckDataByCondition(BuildInfoVo buildInfoVo,
                                                              ParamPage paramPage) {
        Page<BuildInfoDomain> page = new Page<>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (buildInfoVo.getBuildBeginEndDate() != null) {
            buildInfoVo.setBuildBeginEndDate(DateUtils.addDays(buildInfoVo.getBuildBeginEndDate(),
                1));
        }
        if (buildInfoVo.getBuildBeginEndDate() != null) {
            buildInfoVo.setBuildBeginEndDate(DateUtils.addDays(buildInfoVo.getBuildBeginEndDate(),
                1));
        }
        if (buildInfoVo.getBuildFinishEndDate() != null) {
            buildInfoVo.setBuildFinishEndDate(DateUtils.addDays(
                buildInfoVo.getBuildFinishEndDate(), 1));
        }
        // 增加addby
        buildInfoVo.setAddBy(SessionUserUtils.getSessionUserId());
        page = buildInfoService.selectMyCheckByDomainWhere(page, buildInfoVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 新增建投项目
     *
     * @param request
     * @return
     */
    @RequestMapping("/add")
    public String toAdd(HttpServletRequest request) {
        AuthorizationVO authorizationVO = SessionUserUtils.getSessionAttributeForUserDtl();
        StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(authorizationVO.getHrStaffId());
        request.setAttribute("staffName", staffInfo.getStaffName());
        //返回所有交底项中通过审核项目名称
        DisclosePro disclosePro = new DisclosePro();
        disclosePro.setProcessStatus("9");
        List<DisclosePro> selectPreProject = discloseProService.selectByEntityWhere(disclosePro);
        request.setAttribute("allProName", selectPreProject);
        return "ic/lay-buildInfo-add";
    }

    /**
     * 建投信息-新增
     */
//    @SuppressWarnings("rawtypes")
//    @RequestMapping("/save")
//    @ResponseBody
//    public RspVo save(BuildSaveVo buildSaveVo) {
//        String discloseProId = buildSaveVo.getDiscloseProId();
//        DiscloseProVo discloseProVo = discloseProService.selectById(discloseProId);
//        //查出交底项目的其他属性
//        if (discloseProVo != null) {
//            buildSaveVo.setSgCityId(discloseProVo.getSgCityId());
//            buildSaveVo.setProName(discloseProVo.getProName());
//            buildSaveVo.setSumAmount(discloseProVo.getSumAmount());
//            buildSaveVo.setSumCae(discloseProVo.getSumCae());
//            buildSaveVo.setProCode(discloseProVo.getProCode());
//        }
//
//        buildInfoService.savebuildInfo(buildSaveVo);
//        LogUtil.bizLog(LogUtil.LogModelType.PROJECT, LogUtil.AcctionType.ADD,
//            "建投管理 -新增投建基本信息：项目名=" + buildSaveVo.getProName(), null);
//        return RspVo.getSuccessResponse();
//    }

    /**
     * 根据id查询建投项目详细  > 注意：方法命名必须为：toDealOrDetail
     *
     * @param id 投建项目id
     * @return
     * @see
     */
//    @RequestMapping("/toDealOrDetail")
//    public ModelAndView queryById(HttpServletRequest request, String id, String processDealWith) {
//        Map<String, Object> map = new HashMap<String, Object>();
//        BuildSaveVo buildInfo = buildInfoService.queryById(id);
//        List<BuildSub> buildSubList = buildInfo.getBuildSubList();
//        List<MonthCtrlDomain> monthCtrlDomains = monthCtrlService.selectByProCode(buildInfo.getProCode());
//        for (BuildSub buildSub : buildSubList) {
//            for (MonthCtrlDomain monthCtrlDomain : monthCtrlDomains) {
//                if (buildSub.getSubName().trim().equals(monthCtrlDomain.getSubName().trim())) {
//                    Map<String, Object> mapWhere = new HashMap<String, Object>();
//                    mapWhere.put("ctrlSubId", monthCtrlDomain.getSubId());
//                    mapWhere.put("orderCondition", "DELAY_DAYS desc");
//                    List<MonthCtrlMile> monthCtrlMiles = monthCtrlMileService.selectByMapWhere(mapWhere);
//                    buildSub.setDelayedDays(monthCtrlMiles.get(0).getDelayDays());
//                }
//            }
//        }
//        if (buildInfo.getProSignDate() == null || buildInfo.getBuildYears() == null
//            || buildInfo.getOmYears() == null || buildInfo.getBuildInterest() == null
//            || buildInfo.getAssessMemo() == null) {
//            //查合同签订日期
//            ProContract proContract = new ProContract();
//            proContract.setProCode(buildInfo.getProCode());
//            proContract.setProcessStatus("9");
//            List<ProContract> proContractList = proContractService.selectByEntityWhere(proContract);
//            if (proContractList != null && proContractList.size() == 1) {
//                proContract = proContractList.get(0);
//                //建设利息
//                ProContractInvest proContractInvest = new ProContractInvest();
//                proContractInvest.setProContractId(proContract.getId());
//                List<ProContractInvest> investList = proContractInvestService.selectByEntityWhere(proContractInvest);
//                if (investList.size() > 0) {
//                    map.put("proContractInvest", investList.get(0));
//                }
//                map.put("proContract", proContract);
//            }
//        }
//        if (buildInfo.getTakeSignDate() == null) {
//            //承继协议
//            ContractExt contractExt = new ContractExt();
//            contractExt.setProCode(buildInfo.getProCode());
//            contractExt.setProcessStatus("9");
//            contractExt.setExtType("1");
//            List<ContractExt> contractExtList = contractExtService.selectByEntityWhere(contractExt);
//            if (contractExtList != null && contractExtList.size() == 1) {
//                contractExt = contractExtList.get(0);
//                map.put("contractExt", contractExt);
//            }
//        }
//        if (buildInfo.getPackSignDate() == null) {
//            //内部协议评审
//            InnerAgrt innerAgrt = new InnerAgrt();
//            innerAgrt.setProCode(buildInfo.getProCode());
//            innerAgrt.setProcessStatus("9");
//            innerAgrt.setExtType("1");
//            List<InnerAgrt> innerAgrtList = innerAgrtService.selectByEntityWhere(innerAgrt);
//            if (innerAgrtList != null && innerAgrtList.size() == 1) {
//                innerAgrt = innerAgrtList.get(0);
//                map.put("innerAgrt", innerAgrt);
//            }
//        }
//        request.setAttribute("modelDetail", buildInfo);
//        map.put("buildInfo", buildInfo);
//        // 审批flag
//        request.setAttribute("processDealWith", processDealWith);
//        // 审批data
//        processData(request, buildInfo.getProcessId());
//        return new ModelAndView("ic/lay-buildInfo-detail", map);
//    }
    
    /**
     * 投建基本信息-复制单据
     * @return
     */
    @RequestMapping("/toCopy")
    public String toCopy(HttpServletRequest request,String id) {
        AuthorizationVO authorizationVO = SessionUserUtils.getSessionAttributeForUserDtl();
        StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(authorizationVO.getHrStaffId());
        request.setAttribute("staffName", staffInfo.getStaffName());
        //查询id查询单据信息
        BuildSaveVo buildInfo = buildInfoService.queryById(id);
        request.setAttribute("buildInfo", buildInfo);
        return "ic/lay-buildInfo-copy";
    }

    /**
     * 通过项目id查询记录
     */
    @RequestMapping("/getProPlotProId")
    @ResponseBody
    public Map<String, Object> getProPlotProId(HttpServletRequest request) {
        boolean flag = true;
        Map<String, Object> map = new HashMap<>();
        try {
            String discloseProId = request.getParameter("id");
            DiscloseProVo discloseProVo = discloseProService.selectById(discloseProId);
            map.put("discloseProVo", discloseProVo);
        }
        catch (Exception e) {
            log.error("根据项目ID获取项目信息异常", e);
            flag = false;
        }
        map.put("flag", flag);
        return map;
    }

    /**
     * 通过项目id合同相关内容
     */
//    @RequestMapping("/getProContractById")
//    @ResponseBody
//    public Map<String, Object> getProContractById(HttpServletRequest request) {
//        boolean flag = true;
//        Map<String, Object> map = new HashMap<>();
//        try {
//            String discloseProId = request.getParameter("id");
//            //根据交底项目id查询项目procode
//            DiscloseProVo discloseProVo = discloseProService.selectById(discloseProId);
//            String proCode = discloseProVo.getProCode();
//            //查合同签订日期
//            ProContract proContract = new ProContract();
//            proContract.setProCode(proCode);
//            proContract.setProcessStatus("9");
//            List<ProContract> proContractList = proContractService.selectByEntityWhere(proContract);
//            if (proContractList != null && proContractList.size() == 1) {
//                proContract = proContractList.get(0);
//                //建设利息
//                ProContractInvest proContractInvest = new ProContractInvest();
//                proContractInvest.setProContractId(proContract.getId());
//                List<ProContractInvest> investList = proContractInvestService.selectByEntityWhere(proContractInvest);
//                if (investList.size() > 0) {
//                    map.put("proContractInvest", investList.get(0));
//                }
//                map.put("proContract", proContract);
//            }
//            //承继协议
//            ContractExt contractExt = new ContractExt();
//            contractExt.setProCode(proCode);
//            contractExt.setProcessStatus("9");
//            contractExt.setExtType("1");
//            List<ContractExt> contractExtList = contractExtService.selectByEntityWhere(contractExt);
//            if (contractExtList != null && contractExtList.size() == 1) {
//                contractExt = contractExtList.get(0);
//                map.put("contractExt", contractExt);
//            }
//            //内部协议评审
//            InnerAgrt innerAgrt = new InnerAgrt();
//            innerAgrt.setProCode(proCode);
//            innerAgrt.setProcessStatus("9");
//            innerAgrt.setExtType("1");
//            List<InnerAgrt> innerAgrtList = innerAgrtService.selectByEntityWhere(innerAgrt);
//            if (innerAgrtList != null && innerAgrtList.size() == 1) {
//                innerAgrt = innerAgrtList.get(0);
//                map.put("innerAgrt", innerAgrt);
//            }
//        }
//        catch (Exception e) {
//            log.error("根据项目ID获取合同相关信息异常", e);
//            flag = false;
//        }
//        map.put("flag", flag);
//        return map;
//    }

    /**
     * 上传附件
     *
     * @param request
     * @return
     * @throws IOException
     */

    @SuppressWarnings("rawtypes")
    @RequestMapping("/uploadAtt")
    public @ResponseBody RspVo uploadAtt(HttpServletRequest request)
        throws IOException {
        List<String> returnFileStrList = new ArrayList<>();
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
        Map<String, MultipartFile> map = multipartHttpServletRequest.getFileMap();
        if (map != null) {
            for (String name : map.keySet()) {
                MultipartFile file = map.get(name);
                //资料类型
                String types = request.getParameter("types");
                if (StringUtils.isEmpty(types)) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("缺少参数");
                }
                if (file == null) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("上传文件不能为空");
                }
                // 上传文件
                String fileId = IdFactory.getUUIDSerialNumber();
                // 服务器资源路径
                String serverPath = "buildAtt";
                String filePath = FileHelper.upload(file, serverPath);
                returnFileStrList.add(types + "|" + file.getOriginalFilename().trim() + "|"
                                      + fileId + "|" + filePath);
                LogUtil.bizLog(LogUtil.LogModelType.PROJECT, LogUtil.AcctionType.ADD,
                    "上传建投项目附件-文件名:" + filePath + "，文件路径:" + filePath, null);
            }
        }
        return RspVo.getSuccessResponse(returnFileStrList);
    }

}
